<!-- 帖子细节 -->
<template>
  <view class="content" :style="{'height':vHeight + 'vh'}">
    <div><!-- 返回按钮 -->
      <backButton></backButton>
    </div>
    <div class="postBox"> <!-- 帖子内容 -->
      <div><!-- 帖子用户头像名称 -->
        <button class="user-icon" plain="true" style="left:0%; top: 0%; z-index: 1000;"
          @click="() => goToOwnSpace(postElements[0].userId, postElements[0].userName, postElements[0].iconUrl)">
          <image :src="`${bucketUrl}${postElements[0].iconUrl}`" mode="aspectFill"
            style="height: 60px; width: 60px;  border-radius: 100%;">
          </image>
        </button>
        <text class="user-name" style="top: 5%; left:26%; z-index: 1000;">{{postElements[0].userName}}</text>
      </div>
      <div class="postBackground"><!-- 帖子具体内容 -->
        <div class="dailyDetailText1">
          <text>日常类型：{{dailyType[postElements[0].type]}}</text>
          <text>内容：<text class="dailyContent">{{postElements[0].content}}</text></text>

          <!-- 图片区域 -->
          <div style="display: flex;width: 100%; flex-wrap: wrap; margin-top: 5%;">
            <div class="image-box" v-for="(item, index) in imagesArray" :key="index">
              <image class="image-overlay" :src="`${bucketUrl}${item}`" mode="aspectFill" @click="showBigImg(item)">
              </image>
            </div>
          </div>

        </div>
      </div>
      <text class="dailyDetailText2">发布时间：{{shiftTime(postElements[0].createTime)}}</text>
      <!-- 点赞按钮 -->
      <div>
        <button class="dailyLike_Button" plain="true" @click="like()">
          <image :src="likeOrNot" mode="aspectFill" style="height: 20px; width: 20px; "></image>
        </button>
        <text class="dailyLike_Amount">{{postLikeAmount}}</text>
      </div>
    </div>

    <!-- 评论按钮 -->
    <button class="comments_button" @click="toggleMask('show')">发表评论</button>
    <!-- 弹窗 -->
    <ygc-comment ref="ygcComment" :placeholder="'发表评论'" @pubComment="pubComment"></ygc-comment>

    <div style="position: absolute; top: 100%;"> <!-- 评论 -->
      <div class="comments_List" v-for="(item,index) in Comment" :key="index">
        <!-- 评论用户头像名称 -->
        <div style="display: inline;">
          <button class="otheruser-icon" plain="true">
            <image :src="`${bucketUrl}${item.iconUrl}`" mode="aspectFill"
              style="height: 60px; width: 60px;  border-radius: 100%;">
            </image>
          </button>
          <text
            style="font-size: 15px; color: black; margin-top: 5%; position: absolute; top: 0%; left: 10%;">{{item.userName}}</text>
        </div>
        <text style="height: 60px; width: 300px; position: absolute; top: 35%; left: 2%;">{{item.content}}</text>
        <text
          style="font-size: 15px; color: black; position: absolute; bottom: 2%; left: 2%;">{{shiftTime(item.updateTime)}}</text>
        <!-- 点赞按钮 -->
        <div>
          <button class="commentLike_Button" plain="true" @click="likeComment(item)">
            <image :src="commentLikeIcon[item.like]" mode="aspectFill" style="height: 20px; width: 20px; "></image>
          </button>
          <text class="commentLike_Amount">{{item.likes}}</text>
        </div>
      </div>
    </div>
  </view>
</template>

<script>
  import {
    baseUrl,
    bucketUrl
  } from '@/config/baseUrl';
  import backButton from '@/components/backButton/backButton.vue';
  import ygcComment from '@/components/ygc-comment/ygc-comment.vue'

  import {
    getTime
  } from '@/utils/getTime';
  import {
    reqScanAddDaily,
    reqGetCommentList,
    reqLikeBlog,
    reqLikeComment
  } from '@/api/postDetail/dailyPostDetail';

  export default {
    components: {
      backButton,
      ygcComment
    },
    data() {
      return {
        tarId: '',
        tarName: '',
        chooseAvatar: '',
        postElements: getApp().globalData.postDetail,
        dailyType: ['日常分享', '技能提升', '吐槽'],
        commentContent: '', //发布评论输入的内容
        Comment: [], //获取评论列表
        isloading: false,
        startId: 0,
        requestcontent: true,
        vHeight: 200, //页面初始高度
        postLikeAmount: 0,
        likeOrNot: '',

        commentLikeIcon: {
          true: '/static/icon/post/like2.png ',
          false: '/static/icon/post/like1.png'
        },
        like_Icon: '/static/icon/post/like2.png ',
        dislike_Icon: '/static/icon/post/like1.png',

        imagesArray: [],
        bucketUrl: bucketUrl
      }
    },
    onLoad() {
      console.log(this.postElements)

      //将图片路径字符串转成数组
      this.imagesArray = this.postElements[0].imgsUrl.split(',')
      console.log(this.imagesArray)

      if (this.postElements[0].like == true) {
        this.likeOrNot = this.like_Icon;
      } else {
        this.likeOrNot = this.dislike_Icon;
      }
      this.postLikeAmount = this.postElements[0].likes
    },
    onReachBottom() { //触底加载
      if (this.isloading) return //防止加载重复加载
      if (this.requestcontent) {
        this.getComment()
        this.vHeight += 150 //页面大小每次增加100vh
      }
    },
    methods: {
      shiftTime(time) {
        return getTime(time);
      },

      async scanAdd() {
        let result = await reqScanAddDaily(this.postElements[0].id)
        if (result.success) {
          console.log('浏览量+1')
        }
      },

      toggleMask(type) {
        if (!wx.getStorageSync('sessionID')) {
          uni.showToast({
            title: '请先登录!',
            icon: 'none',
            duration: 3000
          });
          return;
        }
        this.$refs.ygcComment.toggleMask(type);
      },
      pubComment(commentContent1) {
        this.$refs.ygcComment.toggleMask();
        console.log(commentContent1);
        this.commentContent = commentContent1;
        this.$refs.ygcComment.content = '';
        var jsonData = JSON.stringify(this.commentContent);
        uni.request({
          url: 'http://localhost:9000/blogService/comment/' + this.postElements[0].id + '/' + 0,
          data: jsonData,
          header: {
            'Content-Type': 'application/json', //自定义请求头信息
            'Access-Control-Allow-Headers': 'appId',
            'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
            'Access-Control-Max-Age': 86400,
            'Authorization': '' + wx.getStorageSync('sessionID')
          },
          method: 'POST',
          success: res => {
            console.log(res.data);
            wx.showToast({
              title: '发布成功',
              icon: 'success',
              mask: true,
              duration: 1000,
              success: function() {
                //弹窗后执行，可以省略
              }
            })
            this.Comment = []; //重新获取数据
            this.startId = 0;
            this.requestcontent = true;
            this.getComment();
          }
        });
      },

      //获取评论 6个
      async getComment() {
        this.isloading = true
        wx.showLoading({
          title: '加载中',
        })

        let result = await reqGetCommentList(this.postElements[0].id, this.startId)
        console.log(result)
        if (result.success) {
          if (result.data.length === 0) { //如果后端评论到底
            this.requestcontent = false
            wx.showToast({
              title: '已经到底啦~',
              icon: 'none',
              duration: 1500,
              mask: true
            })
          } else {
            this.requestcontent = true; //表明后台还有帖子
            result.data.forEach(item => { //将帖子保存进postList
              this.Comment.push(item);
              this.startId = this.Comment[this.Comment.length - 1].id; //获取最后一个帖子的id，用于加载下一波帖子
            })
          }
        }
        wx.hideLoading()
        this.isloading = false
      },

      // 点赞帖子
      async like() {
        if (!wx.getStorageSync('sessionID')) {
          uni.showToast({
            title: '请先登录!',
            icon: 'none',
            duration: 3000
          });
          return;
        }
        //更改图标和点赞量
        if (this.likeOrNot == this.like_Icon) {
          this.likeOrNot = this.dislike_Icon
          this.postLikeAmount--;
        } else if (this.likeOrNot == this.dislike_Icon) {
          this.likeOrNot = this.like_Icon
          this.postLikeAmount++;
        }

        let result = await reqLikeBlog(this.postElements[0].id)
        if (result.success) {
          console.log("点赞或取消点赞成功")
        }
      },

      // 点赞评论
      async likeComment(comment) {
        if (!wx.getStorageSync('sessionID')) {
          uni.showToast({
            title: '请先登录!',
            icon: 'none',
            duration: 3000
          });
          return;
        }

        let result = await reqLikeComment(comment.id)
        if (result.success) {
          console.log("点赞或取消点赞成功");
          this.Comment = [];
          this.startId = 0;
          this.getComment();
        }
      },

      goToOwnSpace(tarId, tarName, chooseAvatar) {
        getApp().globalData.chooseTarId = tarId;
        getApp().globalData.chooseTarName = tarName;
        getApp().globalData.chooseAvatar = baseUrl +
          chooseAvatar;
        uni.navigateTo({
          url: '/pagesA/ownspace/user-space'
        })
      },

      showBigImg(imgs) {
        var path = bucketUrl + imgs;
        console.log(path)
        uni.previewImage({
          current: '',
          urls: [path],
          success: res => {
            console.log(res)
          },
          fail: res => {
            console.log(res)
          }
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  @import url("../../static/css/postdetailstyle.scss");

  .content {
    background-image: url();
    /* 图片素材background_1.jpg */
    background-size: cover;
    background-attachment: fixed;
    height: 200vh;
    width: 100vw;
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .postBox {
    height: 600px;
    width: 320px;
    background-color: #e8e8e8;
    border-radius: 20px;
    border: 1px solid #c8c8c8;
    position: absolute;
    top: 10%;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .postBackground {
    height: 500px;
    width: 280px;
    background-color: #ffffff;
    border-radius: 20px;
    border: 1px solid #c8c8c8;
    position: absolute;
    top: 5%;
  }

  .dailyDetailText1 {
    color: black;
    font-size: 15px;
    display: flex;
    flex-direction: column;
    position: absolute;
    left: 5%;
    top: 10%;
    align-items: flex-start;
  }

  .dailyContent {
    height: 250px;
    width: 220px;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    margin-top: 3%;
    overflow: hidden;
    /* 超出范围省略 */
    -webkit-line-clamp: 6;
    /* 最大行数 */
    text-overflow: ellipsis;
    /* 超出用省略号代替 */
  }

  .dailyDetailText2 {
    color: black;
    font-size: 15px;
    display: flex;
    flex-direction: column;
    position: absolute;
    left: 5%;
    bottom: 5%;
    align-items: flex-start;
  }

  .image-box {
    margin: 5px;
    width: 60px;
    height: 60px;
  }

  .image-overlay {
    width: 100%;
    height: 100%;
  }

  .comments_button {
    background-color: #e8e8e8;
    width: 320px;
    height: 50px;
    border-radius: 15px;
    text-align: center;
    font-size: 20px;
    position: absolute;
    top: 92%;
  }

  .comments_List {
    background-color: #fafafa;
    width: 320px;
    height: 150px;
    border-radius: 15px;
    text-align: center;
    font-size: 15px;
    position: relative;
    margin-top: 15%;
    border: 1px solid #bbbbbb;
  }

  .otheruser-icon {
    position: relative;
    border: none !important;
    border-color: transparent;
    right: 50%;
    bottom: 15%;
  }

  @mixin Like_ButtonStyle() {
    position: absolute;
    border: none !important;
    border-color: transparent;
    right: 10%;
  }

  @mixin Like_AmountStyle() {
    font-size: 15px;
    color: #8a8a8a;
    position: absolute;
    right: 10%;
    text-align: left;
  }

  .dailyLike_Button {
    @include Like_ButtonStyle();
    bottom: 4%;
  }

  .dailyLike_Amount {
    @include Like_AmountStyle();
    bottom: 5%;

  }

  .commentLike_Button {
    @include Like_ButtonStyle();
    bottom: 0%;
  }

  .commentLike_Amount {
    @include Like_AmountStyle() bottom: 3%;
  }
</style>